/*
 * @Descripttion: 
 * @version: 
 * @Author: lily
 * @Date: 2021-05-18 10:13:26
 * @LastEditors: lily
 * @LastEditTime: 2021-05-18 10:59:24
 */
/*
 * @lc app=leetcode.cn id=396 lang=javascript
 *
 * [396] 旋转函数
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number}
 */

//  思想：错位相减法
//  f(n) = f(n-1) - sum + len * nums[len - 1]
//  https://leetcode-cn.com/problems/rotate-function/solution/oncuo-wei-xiang-jian-by-xiaohu9527-ftzh/

//  复杂度：O(n) O(1)

var maxRotateFunction = function (nums) {
    // 计算数组和
    const sum = nums.reduce((a, b) => a + b)
    const len = nums.length
    let pre = 0, curr = 0, res = -Infinity
    // 计算f(0)
    for (let i = 0; i < len; i++) {
        pre += i * nums[i]
    }
    res = Math.max(res, pre)
    // 计算接下来的
    for (let i = 1; i < len; i++) {
        curr = pre + sum - len * nums[len - i]
        res = Math.max(res, curr)
        pre = curr
    }
    return res
};
// @lc code=end
console.log(maxRotateFunction([-1234545, -24354666]));